package com.lagou.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        //String methodName = req.getParameter("methodName");
        /*//判断 执行对应的方法
        if("addCourse".equals(methodName)){
            addCourse(req, resp);
        }else if("findByName".equals(methodName)){
            findByName(req, resp);
        }else if("findByStatus".equals(methodName)){
            findByName(req, resp);
        }*/

        String methodName = null;
        //获取POST请求的Content-Type类型
        String contentType = req.getHeader("Content-Type");
        //判断传递的数据是否为JSON
        if("application/json;charset=utf-8".equals(contentType)){
            //是JSON格式
            String postJSON = getPostJSON(req);
            //将JSON转换为map
            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);
            //从map集合中获取methodName
            methodName  = (String) map.get("methodName");
            //将获取到的数据保存到request域对象中
            req.setAttribute("map",map);

        }else {
            methodName = req.getParameter("methodName");
        }

        //判断执行对应方法
        if(null != methodName){
            //通过反射优化代码
            try {
                //获取字节码文件对象
                Class c = this.getClass();

                //根据传入的方法名获取对应方法对象
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

                //调用method对象的invoke方法
                method.invoke(this,req,resp);

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("请求的功能不存在");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * POST请求格式为 application/json;charset=utf-8
     * 使用该方法进行读取
     */
    public String getPostJSON(HttpServletRequest request){
        try {
            //从request中获取缓冲输入流对象
            BufferedReader reader = request.getReader();
            //创建StringBuffer保存读取的数据
            StringBuffer sb = new StringBuffer();
            //读取
            String line = null;
            while((line = reader.readLine()) != null){
                //将每次读取的数据追加到StringBuffer
                sb.append(line);
            }
            //返回结果
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
